package com.hmo.appshop.mamager.controller;

import com.hmo.appshop.mamager.bean.User;
import com.hmo.appshop.mamager.dto.commom.Result;
import com.hmo.appshop.mamager.dto.user.UserDto;
import com.hmo.appshop.mamager.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
@Api("user")
public class UserController {

    @Value("${number_of_users}")
    private int numberOfUsers;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Resource
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation("注册")
    public Result register(@RequestBody UserDto u) {
        int i = userService.selectAllNumber();
        if (i<numberOfUsers){
            User user = new User();
            user.setUsername(u.getUsername());
            user.setPassword(u.getPassword());
            User register = userService.register(user);
            if (register!=null)
                return new Result().ok(register.getUsername());
            return new Result().serverError("服务器异常");
        }else {
            return new Result().serverError("该后台只允许"+numberOfUsers+"人使用，修改请联系管理员");
        }
    }

    @PostMapping("/login")
    @ApiOperation("登陆")
    public Result login(@RequestBody UserDto u){
        String token = userService.login(u);
        if (token==null)
            return new Result().Gone("用户名或密码错误");
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return new Result().ok(tokenMap);
    }
}
